﻿using System;
using System.Windows;
using Gao.Poker.Domain;
using Gao.Poker.Services;
using Gao.Poker.ViewModel;

namespace Gao.Poker.App.Win
{
    /// <summary>
    /// Interaction logic for MemberWin.xaml
    /// </summary>
    public partial class MemberWin : Window
    {
        public CompetitionViewModel ViewModel { get; set; }
        public Competition Competition { get; set; }

        public MemberWin()
        {
            InitializeComponent();

            btnSearch.Click += Search_Click;
            btnSubmit.Click += Submit_Click;
        }

        void Submit_Click(object sender, RoutedEventArgs e)
        {
            Gao.Poker.Domain.Member member = dgMembers.SelectedItem as Gao.Poker.Domain.Member;
            if(member == null)
            {
                MessageBox.Show("请选择报名的会员","提示信息");
                return;
            }

            CompetitionEntryService service = new CompetitionEntryService();
            if(service.GetMember(member.CardNo, Competition.ID) != null)
            {
                MessageBox.Show("选择的会员已经报名","提示信息");
                return;
            }

            SeatingService ss = new SeatingService();
            var seats = ss.GetNullSeat(Competition.ID);
            if (seats.Count == 0)
            {
                MessageBox.Show("报名已满", "提示信息");
                return;
            }

            CompetitionEntry ce = new CompetitionEntry();
            ce.MemberCardNo = member.CardNo;
            ce.CompetitionID = Competition.ID;
            ce.CreateDt = DateTime.Now;
            
            int indext = new Random().Next(0, seats.Count);
            Seating seat = seats[indext];
            seat.MemberCardNo = member.CardNo;
            ss.Save(seat);
          
            service.Save(ce);

            ViewModel.OnPropertyChanged("Members");
            Close();
        }

        void Search_Click(object sender, RoutedEventArgs e)
        {
            MemberService service = new MemberService();
            var list = service.SearchMembers(txtName.Text, txtCardNo.Text);

            dgMembers.ItemsSource = list;
        }
    }
}
